use hashbrown::HashMap;
use honeybee::prelude::*;
use honeybee::Result;

use super::node::Node;

#[derive(Default)]
pub struct Manager {
    nodes: HashMap<String, Node>,
}

impl Service for Manager {}

#[async_trait::async_trait]
impl Actor for Manager {
    fn name(&self) -> &str {
        "AppNodeManager"
    }

    async fn started(&mut self, ctx: &mut Context<Self>) -> Result<()> {
        info!("AppNodeManager:{} started", ctx.actor_id());
        Ok(())
    }

    async fn stopped(&mut self, _ctx: &mut Context<Self>) {
        info!("AppNodeManager stoped");
    }
}

#[message]
pub struct Register(pub String, pub Addr<TcpStreamActor>);
#[async_trait::async_trait]
impl Handler<Register> for Manager {
    async fn handle(&mut self, _ctx: &mut Context<Self>, msg: Register) -> Result<()> {
        info!("app connecter register:{}", msg.0);
        self.nodes.insert(msg.0, Node::new(msg.1));
        Ok(())
    }
}

#[message]
pub struct Unregister(pub String);
#[async_trait::async_trait]
impl Handler<Unregister> for Manager {
    async fn handle(&mut self, _ctx: &mut Context<Self>, msg: Unregister) -> Result<()> {
        info!("app connecter unregister:{}", msg.0);
        self.nodes.remove(&msg.0);
        Ok(())
    }
}
